using Services;
using UnityEngine;

public class MoveChecker
{
    private readonly GlobalGameCycle gameCycle;
    private readonly Transform m_transform;
    private Vector3 position_previous;

    public bool Moved { get; private set; }
    public Vector2 DeltaPosition { get; private set; }
    public Vector2 Direction => DeltaPosition.normalized;
    private bool active;
    public bool Active
    {
        get => active;
        set
        {
            if (active != value)
            {
                if (value)
                    gameCycle.AttachToGameCycle(EInvokeMode.LateUpdate, OnLateUpdate);
                else
                    gameCycle.RemoveFromGameCycle(EInvokeMode.LateUpdate, OnLateUpdate);
                active = value;
            }
            if (value)
                position_previous = m_transform.position;
            DeltaPosition = Vector2.zero;
        }
    }

    public MoveChecker(Transform transform)
    {
        gameCycle = ServiceLocator.Get<GlobalGameCycle>();
        m_transform = transform;
        Active = true;
    }

    private void OnLateUpdate()
    {
        Moved = position_previous != m_transform.position;
        DeltaPosition = m_transform.position - position_previous;
        position_previous = m_transform.position;
    }
}
